package com.xtm.exercise.utils.uuid;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;

/***
 *@Author: 王磊
 *@CreateTime: 2024-05-08  21:15
 *@Description: hutool包的Snowflake类  推特雪花算法，基于hutool包
 *@title: SnowFlakeUtilV2
 */
@Slf4j
@Component
public class SnowFlakeUtilV2 {


    private static Snowflake SNOWFLAKE = null;

    public static Long getNextId() {
        return SNOWFLAKE.nextId();
    }

    @Bean
    public void  getSnowflakeId(){
        //方式二：根据IP和hostName获取workId和dataCenterId   workerId和dataCenterId是两个参数，分别用于标识工作节点和数据中心。
        long workId = this.getWorkId();
        long dataCenterId = this.getDataCenterId();
        SNOWFLAKE = IdUtil.getSnowflake(workId, dataCenterId);
    }

    /**
     * 根据IP Address 生成workId
     *
     * @return
     */
    private long getWorkId() {
        try {
            String hostAddress = Inet4Address.getLocalHost().getHostAddress();
            log.info("hostAddress========={}", hostAddress);
            int[] ints = StringUtils.toCodePoints(hostAddress);
            int sums = 0;
            for (int b : ints) {
                sums += b;
            }
            return (long) (sums % 32);
        } catch (UnknownHostException e) {
            log.error("根据IP获取workId失败。", e);
            // 如果获取失败，则使用随机数备用
            return RandomUtils.nextLong(0, 31);
        }
    }
    /**
     * 根据HostName 生成dataCenterId
     * @return
     */
    private long getDataCenterId() {
        String hostName = getHostName();
        log.info("hostName========={}", hostName);
        int[] ints = StringUtils.toCodePoints(hostName);
        int sums = 0;
        for (int i : ints) {
            sums += i;
        }
        return (long) (sums % 32);
    }

    /**
     * 获取 hostName
     *   SystemUtils.getHostName() 在mac系统为空处理
     * @return
     */
    public static String getHostName() {
        //获取当前操作系统名称,例如:windows xp,linux 等
        String osName = System.getProperty("os.name");
        String hostName = null;
        if(!StringUtils.startsWithIgnoreCase(osName,"mac")){
            hostName = SystemUtils.getHostName();
        }else{
            try {
                hostName = InetAddress.getLocalHost().getHostName().toUpperCase();
            } catch (UnknownHostException e) {
                hostName = "N/A";
                log.error("获取 hostName错误：", e);
            }
        }
        return hostName;
    }
}
